package com.ltu.biz;

import java.util.Date;
import java.util.Objects;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.ltu.domain.mp_entity.OrderEntity;
import com.ltu.domain.mp_entity.PayRecord;
import com.ltu.domain.mp_entity.customize.ProductServiceEntity;
import com.ltu.domain.mp_entity.customize.ServiceOrderEntity;
import com.ltu.enums.EnumUtils;
import com.ltu.enums.OrderEnums.OrderSource;
import com.ltu.service.OrderDetailService;
import com.ltu.service.OrderService;
import com.ltu.service.PayRecordService;
import com.ltu.service.customize.ProductServiceService;
import com.ltu.service.customize.ServiceOrderService;
import com.ltu.service.mqtt.MqttPushClient;
import com.ltu.util.redis.RedistUtil;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;

/**
 * <p>
 * 学生的报名记录 服务实现类
 * </p>
 *
 * @author 若尘
 * @since 2022-09-20
 */
@Slf4j
@Service
@Transactional(rollbackFor = Exception.class)
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class OrderServiceBiz {
	private final OrderService orderService;
	private final ProductServiceService productServiceService;
	private final OrderDetailService orderDetailService;
	private final ServiceOrderService serviceOrderService;
	private final PayRecordService payRecordService;
	private final RedistUtil  redistUtil;
	private final MqttPushClient  mqttPushClient;
	/**
	 * 支付订单回调 修改订单状态、
	 */
	@Async("customServiceExecutor")
	public void payRecordCallBack(PayRecord payRecord) {
		Date updateDate = new Date();
		try {
			OrderEntity o = orderService.getById(payRecord.getOrderId());
			if (Objects.equals(null, o))
				return;
			if(Objects.equals(o.getPayStatus(), (byte)1))
				return;
			o.setPayStatus((byte)1);
//			 String qrCodeUrl = QRCodeUtil.getQrCodePath(o.getOrderNo(), o.getOrderNo());
//			 o.setOrderQrCode(qrCodeUrl);
			orderService.updateById(o);
			//回调业务
			OrderSource dict =	EnumUtils.indexToEnum(OrderSource.class, o.getSourceDict());	
			switch (dict) {
			case PlaceOrder:  // 下单回调
					//修改商品库存
					ServiceOrderEntity  so = this.serviceOrderService.getById(o.getSourceIds());
					so.setPayStatus(o.getPayStatus().intValue()).setStatus(1);
					this.serviceOrderService.updateById(so);
					ProductServiceEntity  p =  productServiceService.getById(so.getServiceId() );
					p.setSaleAmount(p.getSaleAmount()+1);
					productServiceService.updateById(p);
				break;
			case Reacharge:  // 充值回调
			
				break;
			default:
				break;
			}

		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			payRecord.setStatus((byte) 1).setStatusDesc("支付成功").setUpdateTime(updateDate);
			payRecord.setIsHandle((byte) 1);
			payRecordService.updateById(payRecord);
		}
	}



}
